﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoolERP_Entities;

namespace CoolERP_DAL
{
    public interface IJCCDDAL : IDAL<JCCD>
    {
        List<vJCCD> GetJCCD(Dictionary<string, string> dc, string orderExpr, int? pageIndex, int pageSize, out int totalCount);
        List<JCCDMXBModel> GetJCCDMXB(Guid JCCDID, int iType);
        bool JcdConfirm(Guid ID);
        bool CcdConfirm(Guid ID);
    }

    public class JCCDDAL : BaseDAL<JCCD>, IJCCDDAL
    {
        public JCCDDAL(IUnitOfWork context)
            : base(context)
        {
        }

        public List<vJCCD> GetJCCD(Dictionary<string, string> dc, string orderExpr, int? pageIndex, int pageSize, out int totalCount)
        {
            var result = dataContext.vJCCD.AsQueryable();
            if (dc !=null && dc.Count > 0)
            {
                if (dc.ContainsKey("ID") && !string.IsNullOrEmpty(dc["ID"]))
                {
                    Guid keyVal = Guid.Parse(dc["ID"]);
                    result = result.Where(t => t.ID == keyVal);
                }
                if (dc.ContainsKey("ZT") && !string.IsNullOrEmpty(dc["ZT"]))
                {
                    int keyVal = Convert.ToInt32(dc["ZT"]);
                    result = result.Where(t => t.ZT == keyVal);
                }
                if (dc.ContainsKey("YWLX") && !string.IsNullOrEmpty(dc["YWLX"]))
                {
                    string keyVal = dc["YWLX"];
                    result = result.Where(t => t.YWLXBH == keyVal);
                }
                if (dc.ContainsKey("BH") && !string.IsNullOrEmpty(dc["BH"]))
                {
                    string keyVal = dc["BH"];
                    result = result.Where(t => t.BH.Contains(keyVal));
                }
                if (dc.ContainsKey("Department") && !string.IsNullOrEmpty(dc["Department"]))
                {
                    Guid? keyVal = Guid.Parse(dc["Department"]);
                    result = result.Where(t => t.BMID == keyVal);
                }
                if (dc.ContainsKey("Staff") && !string.IsNullOrEmpty(dc["Staff"]))
                {
                    Guid? keyVal = Guid.Parse(dc["Staff"]);
                    result = result.Where(t => t.CGYID == keyVal);
                }
                if (dc.Keys.Contains("S_Time") && !string.IsNullOrEmpty(dc["S_Time"]))
                {
                    DateTime keyVal = DateTime.ParseExact(Convert.ToDateTime(dc["S_Time"]).ToString("yyyyMMdd"), "yyyyMMdd", System.Threading.Thread.CurrentThread.CurrentCulture);
                    result = result.Where(t => t.RQ >= keyVal);
                }
                if (dc.Keys.Contains("E_Time") && !string.IsNullOrEmpty(dc["E_Time"]))
                {
                    DateTime keyVal = DateTime.ParseExact(Convert.ToDateTime(dc["E_Time"]).AddDays(1).ToString("yyyyMMdd"), "yyyyMMdd", System.Threading.Thread.CurrentThread.CurrentCulture);
                    result = result.Where(t => t.RQ <= keyVal);
                }
            }
            totalCount = result.Count();
            if (!string.IsNullOrEmpty(orderExpr))
                result = SortingExtensions.OrderUsingSortExpression(result, orderExpr);
            if (pageIndex == null)
                return result.ToList();
            else
                return result.Skip(Convert.ToInt32(--pageIndex) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 返回进出仓单明细
        /// </summary>
        /// <param name="ID">进出仓单ID</param>
        /// <param name="iType">1：物料；2：产品；3：包装箱</param>
        public List<JCCDMXBModel> GetJCCDMXB(Guid ID, int iType)
        {
            switch (iType)
            {
                case 1:
                    return GetJCCDMXB_WL(ID);
                case 3:
                    return GetJCCDMXB_BZX(ID);
                default:
                    return GetJCCDMXB_WL(ID);
            }
        }

        /// <summary>
        /// 物料进出仓单明细
        /// </summary>
        public List<JCCDMXBModel> GetJCCDMXB_WL(Guid JCCDID)
        {
            var result = from mx in dataContext.JCCDMXB.Where(t => t.JCCDID == JCCDID)
                         join wl in dataContext.ZL_WL on mx.WPID equals wl.ID
                         join ys in dataContext.CS_YS on new { YSLXBH = wl.YSLXBH, YSBH = wl.YSBH } equals new { YSLXBH = ys.YSLXBH, YSBH = ys.BH }
                         join ck in dataContext.ZL_CK on mx.CKID equals ck.ID
                         join cw in dataContext.ZL_CW on mx.CWID equals cw.ID
                         join dw in dataContext.CS_JBDW on mx.DWBH equals dw.BH
                         join kc in dataContext.KC on new { ID = mx.WPID, CKID = mx.CKID, CWID = mx.CWID } equals new { ID = kc.WPID, CKID = kc.CKID, CWID = kc.CWID }
                         select new JCCDMXBModel
                         {
                             ID = mx.ID,
                             JCCDID = mx.JCCDID,
                             WPID = mx.WPID,
                             WPLX = mx.WPLX,
                             CKMC = ck.MC,
                             CKID = mx.CKID,
                             CWID = mx.CWID,
                             CWMC = cw.QU + "-" + cw.HANG + "-" + cw.LIE + "-" + cw.CENG + "-" + cw.GE,
                             YWLXBH = mx.YWLXBH,
                             SL = mx.SL,
                             YKCSL = kc.SL,
                             DJ = mx.DJ,
                             JCSJ = mx.JCSJ,
                             DWBH = mx.DWBH,
                             DWMC = dw.MC,
                             BH = wl.BH,
                             MC = wl.MC,
                             GG = wl.GG,
                             YS = ys.MC
                         };
            return result.ToList();
        }

        /// <summary>
        /// 包装箱进出仓单明细
        /// </summary>
        public List<JCCDMXBModel> GetJCCDMXB_BZX(Guid JCCDID)
        {
            var result = from mx in dataContext.JCCDMXB
                         join b in dataContext.ZL_CPBZX on mx.WPID equals b.ID
                         join ck in dataContext.ZL_CK on mx.CKID equals ck.ID
                         join cw in dataContext.ZL_CW on mx.CWID equals cw.ID
                         select new JCCDMXBModel
                         {
                             ID = mx.ID,
                             JCCDID = mx.JCCDID,
                             WPID = mx.WPID,
                             WPLX = mx.WPLX,
                             CKMC = ck.MC,
                             CKID = mx.CKID,
                             CWID = mx.CWID,
                             CWMC = cw.QU + "-" + cw.HANG + "-" + cw.LIE + "-" + cw.CENG + "-" + cw.GE,
                             YWLXBH = mx.YWLXBH,
                             SL = mx.SL,
                             YKCSL = mx.YKCSL,
                             DJ = mx.DJ,
                             JCSJ = mx.JCSJ,
                             BH = b.BH,
                             MC = b.MC,
                             BZFS = b.BZFS,
                             WChang = b.WCHANG,
                             WKuan = b.WKUAN,
                             WGao = b.WGAO,
                             TJ = b.TJ,
                             ZL = b.ZL,
                             BZ = b.BZ
                         };
            result = result.Where(t => t.JCCDID == JCCDID);
            return result.ToList();
        }

        /// <summary>
        /// 进仓单确认
        /// </summary>
        public bool JcdConfirm(Guid ID)
        {
            bool result = false;
            dataContext.Connection.Open();
            using (var bs = dataContext.Connection.BeginTransaction())
            {
                try
                {
                    JCCD item = dataContext.JCCD.FirstOrDefault(t => t.ID == ID);
                    item.ZT = 1;
                    IQueryable<JCCDMXB> mxbList = dataContext.JCCDMXB.Where(t => t.JCCDID == ID);
                    foreach (var mx in mxbList)
                    {
                        KC entity = dataContext.KC.FirstOrDefault(t => t.WPID == mx.WPID && t.CWID == mx.CWID && t.CKID == mx.CKID);
                        if (entity == null) //不同仓位新增
                        {
                            entity = new KC();
                            entity.ID = Guid.NewGuid();
                            entity.WPID = mx.WPID;
                            entity.WPLX = mx.WPLX;
                            entity.CKID = mx.CKID;
                            entity.CWID = mx.CWID;
                            entity.SL = mx.SL;
                            entity.ZXDJ = mx.DJ;
                            entity.DW = mx.DWBH;
                            entity.PJDJ = entity.ZXDJ;
                            dataContext.KC.AddObject(entity);
                        }
                        else //同一仓位相加
                        {
                            double ysl = entity.SL;
                            double? ydl = entity.PJDJ;
                            entity.ZXDJ = mx.DJ;
                            entity.SL += mx.SL;
                            entity.PJDJ = (ysl * ydl + mx.DJ * mx.SL) / entity.SL;
                        }
                    }
                    if (Save())
                    {
                        bs.Commit();
                        result = true;
                    }
                }
                catch
                {
                    bs.Rollback();
                    return false;
                }
                finally
                {
                    dataContext.Connection.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 出仓单确认
        /// </summary>
        public bool CcdConfirm(Guid ID)
        {
            bool result = false;
            dataContext.Connection.Open();
            using (var bs = dataContext.Connection.BeginTransaction())
            {
                try
                {
                    JCCD item = dataContext.JCCD.FirstOrDefault(t => t.ID == ID);
                    item.ZT = 1;
                    IQueryable<JCCDMXB> mxbList = dataContext.JCCDMXB.Where(t => t.JCCDID == ID);
                    foreach (var mx in mxbList)
                    {
                        KC entity = dataContext.KC.FirstOrDefault(t => t.WPID == mx.WPID && t.CWID == mx.CWID && t.CKID == mx.CKID);
                        if (entity != null)
                        {
                            if (entity.SL < mx.SL)
                                throw new Exception();
                            else
                                entity.SL -= mx.SL;
                        }
                        else
                            throw new Exception();
                    }
                    if (Save())
                    {
                        bs.Commit();
                        result = true;
                    }
                }
                catch
                {
                    bs.Rollback();
                    return false;
                }
                finally
                {
                    dataContext.Connection.Close();
                }
            }
            return result;
        }
    }
}
